package com.luke.nio.demo;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {

    public static void main(String[] args) throws Exception{

        //创建SocketChannel
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);//非阻塞

        //连接服务端
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8762);
        if(!socketChannel.connect(inetSocketAddress)){
            while (!socketChannel.finishConnect()){
                System.out.println("客户端正在连接服务端，这里不会阻塞，可以执行其他工作");
            }
        }

        //连接成功后发送数据给服务端
        String message = "你好，NIO";
        ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBytes());
        socketChannel.write(byteBuffer);

        //阻塞在控制台不退出
        System.in.read();
    }

}
